package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.common.constants.UserConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealNameMapper;
import com.heima.user.service.ApUserRealNameService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
@RequiredArgsConstructor
public class ApUserRealNameServiceImpl extends ServiceImpl<ApUserRealNameMapper, ApUserRealname> implements ApUserRealNameService {

    private final ApUserMapper apUserMapper;

    private final IWemediaClient wemediaClient;

    /**
     * 获取实名认证列表
     * @param authDto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDto authDto) {
        //1.参数校验
        if (authDto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.分页校验
        authDto.checkParam();
        //3.根据审核状态查询 + 分页查询
        IPage page = new Page(authDto.getPage(), authDto.getSize());
        LambdaQueryWrapper<ApUserRealname>wrapper = new LambdaQueryWrapper<>();
        if (authDto.getStatus() != null){
            wrapper.eq(ApUserRealname::getStatus,authDto.getStatus());
        }
        //4.返回结果
        page = page(page,wrapper);
        ResponseResult responseResult =new PageResponseResult(authDto.getPage(),authDto.getSize(),Math.toIntExact(page.getTotal()));
        responseResult.setData(page.getRecords());
        return responseResult.ok(responseResult);
    }
    /**
     * 根据审核状态更新审核结果
     * @param dto
     * @param status 2审核失败 9审核成功
     * @return
     */
    @Override
    public ResponseResult updateStatus(AuthDto dto, Short status ) {
        //1.参数校验
        if (dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.修改认证状态
        LambdaUpdateWrapper<ApUserRealname> set = Wrappers.<ApUserRealname>lambdaUpdate()
                .eq(ApUserRealname::getId, dto.getId())
                .set(ApUserRealname::getStatus, status);
        if (StringUtils.isNotBlank(dto.getMsg())){
            set.set(ApUserRealname::getReason,dto.getMsg());
        }
        update(set);
        //3.如果审核状态为成功 9 ，需要创建自媒体账户
        // 使用常量调用 equals 方法，避免空指针异常
        if (UserConstants.PASS_AUTH.equals(status)) {
            try {
                // 调用创建用户和作者的方法
                ResponseResult responseResult = createWmUserAndAuthor(dto);
                // 检查返回结果是否为 null
                if (responseResult != null) {
                    return responseResult;
                } else {
                    // 如果返回结果为 null，返回一个默认的错误响应
                    return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"创建用户和作者失败");
                }
            } catch (Exception e) {
                // 捕获异常并返回错误信息
                return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"创建用户和作者时发生异常：" + e.getMessage());
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 创建自媒体用户
     * @param dto
     * @return
     */
    private ResponseResult createWmUserAndAuthor(AuthDto dto) {
        //查询用户认证信息
        ApUserRealname apUserRealname = getById(dto.getId());
        if (apUserRealname == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //查询app端用户信息
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        if (apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //创建自媒体用户
        WmUser wmUser = wemediaClient.findWmUserByName(apUser.getName());
        if (wmUser == null){
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setCreatedTime(new Date());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setStatus(9);
            wemediaClient.saveWmUser(wmUser);
        }
        apUser.setFlag((short) 1);
        apUserMapper.updateById(apUser);
        return null;
    }
}
